package com.stepshop.core.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.stepshop.core.annotation.ActionToken;


/**
 * 表单页面token设置/反之表单重复提交
 * 
 */
public class TokenInterceptor extends HandlerInterceptorAdapter{
	private  Logger logger=Logger.getLogger(getClass());
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
//		logger.info(handler.getClass().getName());
//		logger.info(request.getMethod());
//		logger.info(method.getName());
//		Annotation[] annotations = method.getAnnotations();
//		for(Annotation anno:annotations){
//			RequestMapping rm= (RequestMapping) anno;
//			logger.info(rm.value()[0]);
//		}
//		logger.info(method.getAnnotation(RequestMapping.class).value()[0]);
		ActionToken annotation = method.getAnnotation(ActionToken.class);
		if(annotation!=null){
			BigInteger bi=new BigInteger(64,new Random());
			String tokenKey="token_"+bi.toString(32);
			String tokenValue=bi.toString(36);
			request.getSession().setAttribute(tokenKey,tokenValue);
			System.out.println(tokenKey);
			System.out.println(request.getSession().getAttribute(tokenKey));
			request.setAttribute("token",tokenKey);
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
}
